import sys, os

sys.path.append("../..")
from src.vobjects.item import Item
from src.vobjects.player import Player

from src.config import Config

class PluginVideo:

    watched_time = 0

    def __init__(self, title: str="", playlist_title: str="", url: str="", length: int=0):
        self.title = title
        self.url = url
        self.length = length
        self.playlist_title = playlist_title

    def play(self, play_option: str="", mirror: str="", history=None, time_opt: str=""):
        player = Player()
        player.play(self.url, play_option, self, history, time_opt)

    def download(self, mirror: str=""):
        config = Config()
        
        command = "yt-dlp " + self.url + f" --output '{config.VideoDownloadDirectory}/{self.title}.webm'"

        print(command)

        os.system(command)

    def to_item(self, inHistory: bool=False):
        status = {
            "url" : self.url
        }
        if self.watched_time > 0: status["watched time"] = f"{self.watched_time}s"

        item = Item(
            title=self.playlist_title,
            sstr=self.title,
            parent=self,
            status=status
        )
        if inHistory: item.subtitle = '[+]'

        return item

    def to_history_dict(self):
        hdict = {
            "title" : self.title,
            "url" : self.url,
            "pstitle" : self.playlist_title,
            "watched_time" : self.watched_time
        }

        return hdict

    def from_history_dict(self, hdict):
        self.title = hdict['title']
        self.url = hdict['url']  
        self.playlist_title = hdict['pstitle']
        self.watched_time = hdict['watched_time']

        return self

    def in_history(self, history):
        for hvideo in history.video_list:
            if type(hvideo) == PluginVideo:
                check_title = self.title + self.playlist_title == hvideo.title + hvideo.playlist_title
                if self.url == hvideo.url or check_title:
                    self.watched_time = hvideo.watched_time
                    return True
        return False


